<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>
        <!-- 搜索 -->
        <label class="el-form-item-label">所属公司</label>
          <template>
              <el-select v-model="query.ownerCompanyId" clearable placeholder="请选择" class="filter-item" @keyup.enter.native="crud.toQuery" filterable>
                <el-option
                  v-for="item in companyData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </template>
        <label class="el-form-item-label">骑手姓名</label>
        <el-input v-model="query.userName" clearable placeholder="骑手姓名" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">骑手身份证</label>
        <el-input v-model="query.userIdCard" clearable placeholder="骑手身份证" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <date-range-picker
          v-model="query.policyTime"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          class="date-item"
        />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <template v-slot:right>
           <el-button type="warning" class="filter-item" size="mini" 
           :disabled="crud.selections.length === 0"
           :loading="outAllLoading"
           @click="toOut(crud.selections)"
           >减员导出</el-button>
           <el-button type="primary" class="filter-item" size="mini" 
           @click="openUploadView()"
           >增员导入</el-button>
        </template>
      </crudOperation>
      <el-dialog width="200px;" :visible.sync="dialogUploadVisible" title="增员导入">
        <el-upload
          accept=".xlsx, .xls"
          drag
          :headers="authHeaders"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :action="baseApi + '/api/insured-user/upload'">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传excel（.xls或.xlsx）格式文件 <el-button type="primary" @click="open(baseApi + '/file/upload-template.xls')">下载模版</el-button></div>
      </el-upload>
      </el-dialog>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="600px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
          <el-form-item label="所属公司" prop="ownerCompanyId">
            <template>
              <el-select v-model="form.ownerCompanyId" placeholder="请选择">
                <el-option
                  v-for="item in companyData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-form-item>
          <el-form-item label="骑手姓名" prop="userName">
            <el-input v-model="form.userName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="骑手身份证" prop="userIdCard">
            <el-input v-model="form.userIdCard" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="生效时间" prop="policyStartTime">
            <el-date-picker
              type="datetime"
              align="right"
              v-model="form.policyStartTime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              :style="{ width: '100%' }"
              placeholder="请选择保单生效时间"
              clearable />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="id" v-if="false" />
        <el-table-column prop="userName" label="骑手姓名" />
        <el-table-column prop="userIdCard" label="骑手身份证" />
        <el-table-column prop="ownerCompanyName" label="所属公司">
          <template slot-scope="scope">
            {{ companyData.filter((item,i)=> { return item.id === scope.row.ownerCompanyId } ).map(item => item.name)[0] }}
          </template>
        </el-table-column>
        <el-table-column prop="policyStartTime" label="保单生效时间" />
        <el-table-column prop="policyEntTime" label="保单失效时间" />
        <el-table-column prop="policyStatus" label="在保状态">
          <template slot-scope="scope">
            {{ dict.label.policy_status[scope.row.policyStatus] }}
          </template>
        </el-table-column>
        <el-table-column prop="lastUpdateName" label="操作人" />
        <el-table-column v-if="checkPer(['admin','insured:edit','insured:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
              :disabledDle="true"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudInsuredUser from '@/api/insurance/user'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker'
import { getTopDept } from '@/api/system/dept'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'

const defaultForm = { id: null, createUserId: null, isDeleted: null, createTime: null, lastUpdateTime: null, lastUpdateId: null, ownerId: null, ownerCompanyId: null, userName: null, userIdCard: null, userMobile: null, policyStartTime: null, policyEntTime: null, policyStatus: null }
export default {
  name: 'InsuredUser',
  components: { pagination, crudOperation, rrOperation, udOperation, DateRangePicker },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['policy_status'],
  cruds() {
    return CRUD({ title: '人员', url: 'api/insured-user', idField: 'id', sort: 'id,desc', params: { 'policyStatus': 1, 'isDeleted': 0 }, crudMethod: { ...crudInsuredUser },
      optShow: {
        add: true,
        edit: true,
        del: false,
        reset: false
      }
    })
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  data() {
    return {
      authHeaders: {
        'Authorization': getToken()
      },
      dialogUploadVisible: false,
      permission: {
        add: ['admin', 'insured:add'],
        edit: ['admin', 'insured:edit'],
        del: ['admin', 'insured:del']
      },
      rules: {
        lastUpdateId: [
          { required: true, message: '操作人不能为空', trigger: 'blur' }
        ],
        ownerCompanyId: [
          { required: true, message: '所属公司ID不能为空', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '骑手姓名不能为空', trigger: 'blur' }
        ],
        userIdCard: [
          { required: true, message: '骑手身份证不能为空', trigger: 'blur' }
        ],
        policyStartTime: [
          { required: true, message: '请选择骑手保单生效时间', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'ownerCompanyId', display_name: '所属公司ID' },
        { key: 'userName', display_name: '骑手姓名' },
        { key: 'userIdCard', display_name: '骑手身份证' },
        { key: 'policyStartTime', display_name: '保单生效时间' }
      ],
      companyData: [],
      outAllLoading: false
    }
  },
  created() {
    getTopDept().then(res => {
      this.companyData = res
    })
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    toOut(data) {
      this.$confirm(`确认将选中的${data.length}个人员移出?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        if (data instanceof Array) {
          data.forEach(val => {
            ids.push(val.id)
          })
        } else {
          ids.push(data.id)
        }
        this.outAllLoading = true
        crudInsuredUser.batchOut(ids).then(res => {
          this.crud.notify('减员成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.refresh()
        })
      }).catch(() => {
      })
    },
    openUploadView() {
      this.dialogUploadVisible = true
    },
    handleUploadSuccess(response, file, fileList) {
      this.dialogUploadVisible = false
      this.crud.notify('导入成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.crud.refresh()
    },
    handleUploadError(response, file) {
      this.crud.notify(JSON.parse(response.message).message, CRUD.NOTIFICATION_TYPE.ERROR)
    },
    open(url) {
      window.open(url, '_blank')
    }
  }

}
</script>

<style scoped>

</style>
